//
//  IMB_CameraViewController.m
//  BabyNow
//
//  Created by 刘泽琛 on 14-4-23.
//  Copyright (c) 2014年 iMobile. All rights reserved.
//
//倒计时
static int i = 30;

#import "IMB_CameraViewController.h"
#import <AVFoundation/AVAudioSession.h>
#import <QuartzCore/QuartzCore.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "IMB_BrowseViewController.h"
#import "BN_CreateContentViewController.h"
#import "iMB_CameraAnimation.h"

@interface IMB_CameraViewController () <AVCaptureManagerDelegate,SendResultUrl,ZYQAssetPickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    NSTimeInterval startTime;
    NSString *videoOrPhoto;
    NSURL *localVideoUrl;
    
    BOOL isNeededToSave;
    EncodeToMP4 *encodeToMP4;
    iMB_CameraAnimation *cameraAnimation;
    
    UIImageView *selectPhoto;
    UIImageView *focusImageView;
    ALAssetsLibrary *library;
    UIImagePickerController *videoPicker;
}

@property (nonatomic, strong) AVCaptureManager *captureManager;
@property (nonatomic, assign) NSTimer *timer;
@property (nonatomic, strong) UIImage *recStartImage;

@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet LRGlowingButton *exitBtn;
@property (weak, nonatomic) IBOutlet UILabel *statusLabel;
@property (weak, nonatomic) IBOutlet UIButton *recBtn;
@property (weak, nonatomic) IBOutlet LRGlowingButton *backPhotoAction;

// 底层工具栏切换
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIImageView *lastPhoto;

@end

@implementation IMB_CameraViewController


#pragma mark 判断设备是否禁止麦克风、摄像头
- (void)detectionMicrophoneCameraIsBind {
    // 前后摄像头
    // AVCaptureManager.h 中设置

    // 麦克风
    if ([[AVAudioSession sharedInstance] respondsToSelector:@selector(requestRecordPermission:)]) {
        [[AVAudioSession sharedInstance] performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
            if (granted) {
            }
            else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[[UIAlertView alloc] initWithTitle:@"提示"
                                                 message:@"您的麦克风处于禁止状态，可以在手机‘设置-隐私-麦克风’中启用"
                                                delegate:nil
                                       cancelButtonTitle:nil
                                       otherButtonTitles:@"好",nil] show];
                });
            }
        }];
    }
}

// 设备方向
- (void)getDeviceDirection {
    UIDevice *device = [UIDevice currentDevice];
    switch (device.orientation) {
        case UIDeviceOrientationFaceUp:
            NSLog(@"螢幕朝上平躺");
            break;
            
        case UIDeviceOrientationFaceDown:
            NSLog(@"螢幕朝下平躺");
            break;
            
            //系統無法判斷目前Device的方向，有可能是斜置
        case UIDeviceOrientationUnknown:
            NSLog(@"未知方向");
            break;
            
        case UIDeviceOrientationLandscapeLeft:
            self.screenDirectionValue = 2;
            NSLog(@"螢幕向左橫置");
            //imgView.transform = CGAffineTransformMakeRotation((CGFloat)(-90 * M_PI / 180.0));
            break;
            
        case UIDeviceOrientationLandscapeRight:
            self.screenDirectionValue = 3;
            NSLog(@"螢幕向右橫置");
            //imgView.transform = CGAffineTransformMakeRotation((CGFloat)(90 * M_PI / 180.0));
            break;
            
        case UIDeviceOrientationPortrait:
            self.screenDirectionValue = 1;
            NSLog(@"螢幕直立");
            break;
            
        case UIDeviceOrientationPortraitUpsideDown:
            NSLog(@"螢幕直立，上下顛倒");
            break;
            
        default:
            NSLog(@"無法辨識");
            break;
    }
}

#pragma mark 初始化
- (id)initWithUIChange:(DisPlayStatusBar)disPlayStatus {
    if (self = [super init]) {
        self.disPlayStatus = disPlayStatus;
    }
    return self;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 对焦
    // AVCaptureDevice*camDevice =[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    //[camDevice removeObserver:self forKeyPath:@"adjustingFocus"];
    // timer释放
    [self timeCancel];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // UI
    self.statusLabel.text = @"30";
    
    // 对焦
    // AVCaptureDevice*camDevice =[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    // int flags = NSKeyValueObservingOptionNew;
    // [camDevice addObserver:self forKeyPath:@"adjustingFocus" options:flags context:nil];
    // 检测相机摄像头、麦克风
    //
    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];

    [self detectionMicrophoneCameraIsBind];
    [self getDeviceDirection];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    // bug
    self.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, FULLSCREEN_HEIGHT);
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = YES;
    _topView.backgroundColor = [UIColor colorWithRed:0.1 green:0.11 blue:0.11 alpha:1];
    _scrollView.backgroundColor = [UIColor colorWithRed:0.1 green:0.11 blue:0.11 alpha:1];
    _recBtn.backgroundColor = [UIColor clearColor];
    _backPhotoAction.backgroundColor = [UIColor clearColor];
    
    // 相册中的imgs
    self.imgfromCameraArr = [[NSMutableArray alloc]init];
    
    // SYSTEM UI
    self.captureManager = [[AVCaptureManager alloc] initWithPreviewView:self.view];
    self.captureManager.delegate = self;
    
    // self.cap
    [self.recBtn setImage:[UIImage imageNamed:@"shexiang"] forState:UIControlStateNormal];
    [self.backPhotoAction setImage:[UIImage imageNamed:@"zhaoxiang"] forState:UIControlStateNormal];
    self.backPhotoAction.highlightedGlowColor = [UIColor whiteColor];
    self.backPhotoAction.glowsWhenHighlighted = YES;
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                 action:@selector(handleDoubleTap:)];
    tapGesture.numberOfTapsRequired = 2;
    [self.view addGestureRecognizer:tapGesture];
    
    /*// 焦点UIImageView
    focusImageView = [[UIImageView alloc]initWithFrame:CGRectMake((SCREEN_WIDTH-100)/2, (384-100)/2+44, 100, 100)];
    focusImageView.image = [UIImage imageNamed:@"focus-crosshair"];
    [self.view addSubview:focusImageView];
    focusImageView.hidden = YES;*/
    
    // 返回上一视图按钮
    self.exitBtn.glowsWhenHighlighted = YES;
    self.exitBtn.highlightedGlowColor = [UIColor whiteColor];
    [self.exitBtn addTarget:self action:@selector(closeTapped:) forControlEvents:UIControlEventTouchUpInside];

    // 倒计时
    self.statusLabel.text = @"30";
    
    // ScrollView
    [self.scrollView setContentSize:CGSizeMake(SCREEN_WIDTH*2, 119)];
    self.scrollView.pagingEnabled = YES;
    self.scrollView.directionalLockEnabled = YES;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.scrollEnabled = NO;
    // scrollView适配高度
    NSInteger viewHeight = FULLSCREEN_HEIGHT;
    if (viewHeight <= 480) {
        switch (MAIN_VERSION) {
            case 6:
                self.scrollView.frame = CGRectMake(0, FULLSCREEN_HEIGHT-119, SCREEN_WIDTH, 119);
                self.lastPhoto.frame = CGRectMake(14, (self.scrollView.frame.size.height-43)/2, 43, 43);
                self.recBtn.frame = CGRectMake((SCREEN_WIDTH-73)/2, (self.scrollView.frame.size.height-73)/2, 73, 73);
                self.backPhotoAction.frame = CGRectMake(260, (self.scrollView.frame.size.height-50)/2, 50, 50);
                break;
            default:
                
                self.scrollView.frame = CGRectMake(0, FULLSCREEN_HEIGHT-119, SCREEN_WIDTH, 119);
                self.lastPhoto.frame = CGRectMake(14, (self.scrollView.frame.size.height-40)/2, 43, 43);
                self.recBtn.frame = CGRectMake((SCREEN_WIDTH-73)/2, (self.scrollView.frame.size.height-73)/2, 73, 73);
                self.backPhotoAction.frame = CGRectMake(260, (self.scrollView.frame.size.height-50)/2, 50, 50);
                break;
        }
    }
    
    // 选取缩略图
    __block IMB_CameraViewController *blockSelf_ = self;
    NSString *XHCameraModeVideo = ALAssetTypeVideo;
    [self updateLibraryButtonWithCameraMode:XHCameraModeVideo didFinishcompledBlock:^(UIImage *thumbnail) {
        if (thumbnail) {
            blockSelf_.lastPhoto.image = thumbnail;
        }else {
            blockSelf_.lastPhoto.image = [UIImage imageNamed:@"zhanweifu_camera"];
        }
    }];
    
    // 左侧图片UIImageView以及得到最后一张图片
    self.lastPhoto.userInteractionEnabled = YES;
    UITapGestureRecognizer *openCameraTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(loadVideoPickerAction)];
    [self.lastPhoto addGestureRecognizer:openCameraTap];
    self.lastPhoto.layer.masksToBounds = YES;
    self.lastPhoto.layer.cornerRadius = 6.0;
    self.lastPhoto.layer.borderWidth = 0.1;
    self.lastPhoto.layer.borderColor = [[UIColor whiteColor] CGColor];
    
    [self loadSecondView];
    [self loadCameraAnimationView];
    
    // 通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(finishedAction:) name:@"K_DIY_CAMERA_VC" object:nil];
}

- (void)loadSecondView {
    UIView *rightView = [[UIView alloc]init];
    NSInteger viewHeight = FULLSCREEN_HEIGHT;
    if (viewHeight <= 480) {
        rightView.frame = CGRectMake(SCREEN_WIDTH, 0, SCREEN_WIDTH, 119);
    }else {
        rightView.frame = CGRectMake(SCREEN_WIDTH, 0, SCREEN_WIDTH, 184);
    }
    // 照相部分
    [self.scrollView addSubview:rightView];
    UIButton *zxBtn = [[UIButton alloc]initWithFrame:CGRectMake((SCREEN_WIDTH-73)/2, (rightView.frame.size.height-73)/2, 73, 73)];
    [zxBtn addTarget:self action:@selector(takePhotoAction) forControlEvents:UIControlEventTouchUpInside];
    [zxBtn setImage:[UIImage imageNamed:@"zhaoxiang"] forState:UIControlStateNormal];
    [rightView addSubview:zxBtn];
    
    // 摄像小图
    LRGlowingButton *sxBtn = [[LRGlowingButton alloc]initWithFrame:CGRectMake(14, (rightView.frame.size.height-50)/2, 50, 50)];
    sxBtn.highlightedGlowColor = [UIColor whiteColor];
    sxBtn.glowsWhenHighlighted = YES;
    [sxBtn addTarget:self action:@selector(backVideo) forControlEvents:UIControlEventTouchUpInside];
    [sxBtn setImage:[UIImage imageNamed:@"shexiangsmall"] forState:UIControlStateNormal];
    [rightView addSubview:sxBtn];
    
    // 选择照片
    selectPhoto = [[UIImageView alloc]initWithFrame:CGRectMake(260, (rightView.frame.size.height-43)/2, 43, 43)];
    selectPhoto.layer.masksToBounds = YES;
    selectPhoto.layer.cornerRadius = 6.0;
    selectPhoto.layer.borderWidth = 0.1;
    selectPhoto.layer.borderColor = [[UIColor whiteColor] CGColor];
    
    // 选取缩略图
    NSString *XHCameraModeVideo = ALAssetTypePhoto;
    [self updateLibraryButtonWithCameraMode:XHCameraModeVideo didFinishcompledBlock:^(UIImage *thumbnail) {
        selectPhoto.image = thumbnail;
        if (thumbnail) {
            selectPhoto.image = thumbnail;
        }else {
            selectPhoto.image = [UIImage imageNamed:@"zhanweifu_camera"];
        }
    }];
    
    UITapGestureRecognizer *selectPhotoTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(openCameraTapped:)];
    selectPhoto.userInteractionEnabled = YES;
    [selectPhoto addGestureRecognizer:selectPhotoTap];
    [rightView addSubview:selectPhoto];
}

- (void)loadCameraAnimationView {
    cameraAnimation = [[iMB_CameraAnimation alloc]init];
    if (SCREEN_HEIGHT > 480) {
        cameraAnimation.frame = CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_WIDTH);
    }else {
        cameraAnimation.frame = CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_WIDTH-20);
    }
    cameraAnimation.backgroundColor = [UIColor clearColor];
    [cameraAnimation initWithCameraAnimation];
    [self.view addSubview:cameraAnimation];
}

#pragma mark 手势
#pragma mark - Gesture Handler

- (void)handleDoubleTap:(UITapGestureRecognizer *)sender {
    
    [self.captureManager toggleContentsGravity];
}

// 用户关闭
- (void)closeTapped:(UITapGestureRecognizer *)tap {
    [self releaseResource];
    self.disPlayStatus(@"disPlay");
    [self dismissViewControllerAnimated:NO completion:NULL];
}

- (void)timerHandler:(NSTimer *)timer {
    i--;
    if (i==0) {
        // 停止录像
        [self recButtonTapped:nil];
    }
    self.statusLabel.text = [NSString stringWithFormat:@"%d",i];
}

#pragma mark
#pragma mark - 摄像完成后 进行压缩处理
- (void)didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL error:(NSError *)error {
    
    if (error) {
        NSLog(@"error:%@", error);
        return;
    }
    
    if (!isNeededToSave) {
        return;
    }
    // 暂不保存
    // [self saveRecordedFile:outputFileURL];
    // 通过URL来进行压缩处理
    encodeToMP4 = [[EncodeToMP4 alloc]init];
    encodeToMP4.delegate = self;
    [encodeToMP4 start:outputFileURL hasVideo:YES isSave:YES];
}

#pragma mark - IBAction
- (void)finishedAction:(NSNotification *)notification {
    [self releaseResource];
    [self dismissViewControllerAnimated:NO completion:^{
        [[NSNotificationCenter defaultCenter]postNotificationName:@"K_CAMERA_END" object:nil];
    }];
}

- (IBAction)backPhotoTapped:(id)sender {
    if (self.isVCRing) {
        [SVProgressHUD showErrorWithStatus:@"拍摄视频中,请勿中断"];
    }else{
        // 照相
        // 录像点消失
        CGPoint position = CGPointMake(320, 0);
        [self.scrollView setContentOffset:position animated:YES];
        self.statusLabel.hidden = YES;
        
        // 照相动画
        [cameraAnimation viewToClose];
    }
}

- (void)backVideo {
    CGPoint position = CGPointMake(0, 0);
    [self.scrollView setContentOffset:position animated:YES];
    self.statusLabel.hidden = NO;
    // 照相动画
    [cameraAnimation viewToClose];
}

#pragma mark
#pragma mark 照相 录像
- (void)takePhotoAction {
    [self getDeviceDirection];
    [[self captureManager] captureStillImage];
}

- (IBAction)recButtonTapped:(id)sender {
    self.isLocal = NO;
    self.isVCRing = YES;
    // REC START
    if (!self.captureManager.isRecording) {
        // 设备方向
        [self getDeviceDirection];
        
        // change UI
        UIImage *startRecBtn = [UIImage imageNamed:@"paisheing"];
        [self.recBtn setImage:startRecBtn
                     forState:UIControlStateNormal];
        
        i = 30;
        self.statusLabel.text = @"30";
        if (!self.timer) {
            self.timer = [NSTimer scheduledTimerWithTimeInterval:1
                                                          target:self
                                                        selector:@selector(timerHandler:)
                                                        userInfo:nil
                                                         repeats:YES];
        }
        [self.captureManager startRecording];
    }
    // REC STOP
    else {
        [SVProgressHUD showWithStatus:@"视频压缩中..." maskType:SVProgressHUDMaskTypeBlack];
        [self timeCancel];
        isNeededToSave = YES;
        self.isVCRing = NO;
        [self.captureManager stopRecording];
        // change UI
        UIImage *stopRecBtn = [UIImage imageNamed:@"shexiang"];
        [self.recBtn setImage:stopRecBtn
                     forState:UIControlStateNormal];
    }
}

// timer关闭
- (void)timeCancel {
    [self.timer invalidate];
    self.timer = nil;
}

- (void)selectVideoTapped:(UITapGestureRecognizer *)tap {
    // code...
}

// 捕获图片后
- (void)captureManagerStillImageCaptured:(AVCaptureManager *)captureManager
{
    CFRunLoopPerformBlock(CFRunLoopGetMain(), kCFRunLoopCommonModes, ^(void) {
    });
}

- (void)openCameraTapped:(UITapGestureRecognizer *)tap {
    ZYQAssetPickerController *picker = [[ZYQAssetPickerController alloc] init];
    picker.maximumNumberOfSelection = 10;
    picker.assetsFilter = [ALAssetsFilter allPhotos];
    picker.showEmptyGroups = NO;
    picker.delegate = self;
    picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        if ([[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo]) {
            NSTimeInterval duration = [[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyDuration] doubleValue];
            return duration >= 5;
        } else {
            return YES;
        }
    }];
    [self presentViewController:picker animated:YES completion:NULL];
}

-(void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets{
        
    __weak typeof(self) cameraVc = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // src.contentSize = CGSizeMake(assets.count*src.frame.size.width, src.frame.size.height);
        dispatch_async(dispatch_get_main_queue(), ^{
            // pageControl.numberOfPages = assets.count;
        });
        
        for (int i=0; i<assets.count; i++) {
            ALAsset *asset=assets[i];
            UIImage *tempImg = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
            [cameraVc.imgfromCameraArr addObject:tempImg];
        }
        cameraVc.sendDict = @{@"fileData": @"无",@"fileImg":cameraVc.imgfromCameraArr,@"fileType":@"1"};
        [cameraVc performSelectorOnMainThread:@selector(openBrowseVc:) withObject:nil waitUntilDone:YES];
    });
}

- (void)captureManager:(AVCaptureManager *)captureManager didFailWithError:(NSError *)error {
    [SVProgressHUD showErrorWithStatus:@"操作失败"];
}

- (void)saveRecordedFile:(NSURL *)recordedFile {
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        
        ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
        [assetLibrary writeVideoAtPathToSavedPhotosAlbum:recordedFile
                                         completionBlock:
         ^(NSURL *assetURL, NSError *error) {
             
             dispatch_async(dispatch_get_main_queue(), ^{
                 
                 NSString *title;
                 NSString *message;
                 
                 if (error != nil) {
                     
                     title = @"保存失败";
                     message = [error localizedDescription];
                 }
                 else {
                     title = @"保存成功";
                     message = nil;
                 }
                 
                 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                                 message:message
                                                                delegate:nil
                                                       cancelButtonTitle:@"OK"
                                                       otherButtonTitles:nil];
                 [alert show];
             });
         }];
    });
}

#pragma mark
#pragma mark 视频压缩后，返回的URL
- (void)openBrowseVc:(id)result {
    IMB_SaveCameraInfo *saveCameraInfo = [IMB_SaveCameraInfo sharedSaveCameraInfo];
    saveCameraInfo.cameraDict = self.sendDict;
    [self releaseResource];
    [self dismissViewControllerAnimated:NO completion:^{
        // K_DIY_CAMERA_VC
        [[NSNotificationCenter defaultCenter]postNotificationName:@"K_CAMERA_END" object:nil];
    }];
}

- (void)backResultDatainfo:(NSURL *)url {
    // 取消消息提示
    [SVProgressHUD dismiss];
    
    IMB_BrowseViewController *browseContent = [[IMB_BrowseViewController alloc]init];
    browseContent.webURL = url;
    browseContent.screenDirectionValue = self.screenDirectionValue;
    browseContent.isLocal = self.isLocal;
    browseContent.videoOrPhoto = @"video";
    [self presentViewController:browseContent animated:YES completion:NULL];
}

- (void)backImgInfo:(UIImage *)image {
    IMB_BrowseViewController *browseContent = [[IMB_BrowseViewController alloc]init];
    browseContent.imgInfo = image;
    browseContent.screenDirectionValue = self.screenDirectionValue;
    browseContent.videoOrPhoto = @"photo";
    [self presentViewController:browseContent animated:YES completion:NULL];
}

#pragma mark
#pragma mark  imagePickerController
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
	NSLog(@"%@",[info valueForKey:UIImagePickerControllerMediaURL]);
    localVideoUrl = [info valueForKey:UIImagePickerControllerMediaURL];
    [picker dismissViewControllerAnimated:YES completion:^{
        [self getVideoTime];
    }];
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark
#pragma mark 工具方法

/*// 自动对焦callback
-(void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context {
    if([keyPath isEqualToString:@"adjustingFocus"]){
        BOOL adjustingFocus =[[change objectForKey:NSKeyValueChangeNewKey] isEqualToNumber:[NSNumber numberWithInt:1]];
        if (adjustingFocus) {
            focusImageView.hidden = NO;
        }else {
            focusImageView.hidden = YES;
        }
    }
}*/

-(void)screenShotRect:(CGRect)aRect //arect 想要截图的区域
{
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(SCREEN_WIDTH, FULLSCREEN_HEIGHT), YES, 0);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    CGImageRef imageRef = viewImage.CGImage;
    
    CGRect rect = aRect; //这里可以设置想要截图的区域
    CGImageRef imageRefRect =CGImageCreateWithImageInRect(imageRef, rect);
    UIImage *sendImage = [[UIImage alloc] initWithCGImage:imageRefRect];
    NSData *imageViewData = UIImagePNGRepresentation(sendImage);
    
    // 第一，保存到沙盒
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:@"zone.png"];
    NSLog(@"%@", savedImagePath);
    [imageViewData writeToFile:savedImagePath atomically:YES];
    CGImageRelease(imageRefRect);
    
    //第二，保存到相册
    UIImage *image = [UIImage imageWithData:imageViewData];
    UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);
}

// 得到视频的时长
- (void)getVideoTime {
    AVAsset *avAsset = [AVAsset assetWithURL:localVideoUrl];
    CMTime assetTime = [avAsset duration];
    Float64 duration = CMTimeGetSeconds(assetTime);
    NSLog(@"视频时长 %f\n",duration);
    
    if (duration <= 30) {
        encodeToMP4 = [[EncodeToMP4 alloc]init];
        encodeToMP4.delegate = self;
        [encodeToMP4 start:localVideoUrl hasVideo:YES isSave:NO];
    }else {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"" message:@"您选择的视频时长大于30秒,请选择时长小于30秒的视频." delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
    }

}

// 得到视频文件夹
- (void)loadVideoPickerAction {
    
    if (self.isVCRing) {
        [SVProgressHUD showErrorWithStatus:@"拍摄视频中,请勿中断"];
    }else{
        self.isLocal = YES;
        if (videoPicker == nil) {
            videoPicker = [[UIImagePickerController alloc] init];
            videoPicker.delegate = self;
        }
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum] == YES) {
            videoPicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            videoPicker.mediaTypes = [NSArray arrayWithObject:(NSString *)kUTTypeMovie];
            [self presentViewController:videoPicker animated:YES completion:nil];
        }
    }
}

// 从相册中抽出最后一张图片
- (void)updateLibraryButtonWithCameraMode:(NSString *)cameraMode didFinishcompledBlock:(void (^)(UIImage *thumbnail))compled {
    __block NSString *assetPropertyType = nil;
    __block NSMutableArray *assets = [[NSMutableArray alloc] init];
    //    if (cameraMode == XHCameraModePhoto) {
    //        assetPropertyType = [ALAssetTypePhoto copy];
    //    } else if (cameraMode == XHCameraModeVideo) {
    //        assetPropertyType = [ALAssetTypeVideo copy];
    //    }
    assetPropertyType = cameraMode;
    
    void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop)
    {
        if (group == nil)
        {
            return;
        }
        *stop = YES;
        
        __block int num = 0;
        [group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop)
         {
             if(result == nil)
             {
                 return;
             }
             __block ALAsset *assetResult = result;
             num++;
             NSInteger numberOf = [group numberOfAssets];
             
             NSString *al_assetPropertyType = [assetResult valueForProperty:ALAssetPropertyType];
             if ([al_assetPropertyType isEqualToString:assetPropertyType]) {
                 [assets addObject:assetResult];
             }
             
             if (num == numberOf) {
                 UIImage *img = [UIImage imageWithCGImage:[[assets lastObject] thumbnail]];
                 dispatch_async(dispatch_get_main_queue(), ^{
                     if (compled) {
                         compled(img);
                     }
                 });
             }
         }];
    };
    
    // Group Enumerator Failure Block
    void (^assetGroupEnumberatorFailure)(NSError *) = ^(NSError *error) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            UIImage *img = [UIImage imageNamed:@"photo_Library.png"];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (compled) {
                    compled(img);
                }
            });
        });
    };
    // Enumerate Albums
    ALAssetsLibrary *library_ = [[ALAssetsLibrary alloc] init];
    [library_ enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
                            usingBlock:assetGroupEnumerator
                          failureBlock:assetGroupEnumberatorFailure];
}

#pragma mark
#pragma mark 资源

- (void)releaseResource {
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"K_CAMERA_END" object:nil];
    encodeToMP4.delegate = nil;
    encodeToMP4 = nil;
    cameraAnimation = nil;
    self.captureManager.delegate = nil;
    self.captureManager = nil;
    [self timeCancel];
    
}

- (void)dealloc
{
    [self releaseResource];
}

@end
